package com.calvin.study.LinkedList;

public class LinkedListDemo01 {

	public static void main(String[] args) {
		
		Node mr = new Node("鸣人");
		Node xy = new Node("小樱");
		Node zz = new Node("佐助");

		// 连接三个节点，形成双向链表
		// mr -> xy -> zz
		mr.next = xy;
		xy.next = zz;

		// zz-> xy -> mr
		zz.prev = xy;
		xy.prev = mr;

		Node first = mr;// 双向链表的首节点
		Node last = zz;// 双向链表的尾节点
		
		linkedListForEach(first);

		System.out.println("=========双向链表添加元素==========");
		// 在小樱和佐助中间加一个大蛇丸
		Node dsw = new Node("大蛇丸");
		//小樱的next节点是大蛇丸
		xy.next = dsw;
		//大蛇丸的next节点是佐助
		dsw.next = zz;
		
		//佐助的前一个节点是大蛇丸
		zz.prev = dsw;
		//大蛇丸的前一个节点是小樱
		dsw.prev = xy;
	
		linkedListForEach(first);
		
		
		linkLast("猫老大");
	}
	
	public static void linkLast(String item) {
		Node first = null;
		Node last = null;
		Node l = last;
		Node mr = new Node(l, item, null);
		last = mr;
		if(l == null) {
			first = mr;
		}else {
			l.next = mr;
		}
	}

	public static void linkedListForEach(Node obj) {
		System.out.println("=========双向链表从头到尾进行遍历==========");
		while (true) {
			if (null == obj) {
				break;
			}
			System.out.println(obj);
			obj = obj.next;// 循环指向下一个节点
		}
	}
}

//定义Node类，Node对象为双向链表的一个节点
class Node {

	public Object item; // 存放数据

	public Node prev;// 指向前一个节点

	public Node next;// 指向后一个节点

	public Node(Object item) {
		this.item = item;
	}
	

	public Node( Node prev ,Object item, Node next) {
		this.item = item;
		this.prev = prev;
		this.next = next;
	}



	@Override
	public String toString() {
		return "Node name = " + item;
	}

}
